package com.ssish.saas.eccs.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Map;
import java.util.TreeMap;

/**
 * 3DES加密工具类
 */
public class EncryptUtil {
	public static final String defCharset = "UTF-8";
	/**
     * 密钥算法
     */
    public static final String KEY_ALGORITHM    = "DESede";
    
    public static void main(String[] args) throws Exception {
    	//加密测试
		System.out.println("");
	}
    
    public static String encrypt(String pstJson,String parKey,String pstIV ) throws Exception {
        try {
    
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = pstJson.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            
            SecretKeySpec keyspec = new SecretKeySpec(parKey.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(pstIV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new sun.misc.BASE64Encoder().encode(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
       }
    
    public static String desEncrypt(String data,String parKey,String pstIV ) throws Exception {
        try{
             byte[] encrypted1 =  new sun.misc.BASE64Decoder().decodeBuffer(data);
            
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(parKey.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(pstIV.getBytes());
            
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);


            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    
	  
   
    
    
    
    
  
    
    
    
    
    
   
    
    
    
    
 
   
}

